package com.duofan.gmall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.duofan.gmall.common.to.mq.SeckillOrderTo;
import com.duofan.gmall.common.utils.R;
import com.duofan.gmall.common.vo.MemberRespVo;
import com.duofan.gmall.seckill.feign.CouponFeignService;
import com.duofan.gmall.seckill.feign.ProductFeignService;
import com.duofan.gmall.seckill.interceptor.LoginUserInterceptor;
import com.duofan.gmall.seckill.service.SeckillService;
import com.duofan.gmall.seckill.to.SeckillSkuRedisTo;
import com.duofan.gmall.seckill.vo.SeckillSessionsWithSkus;
import com.duofan.gmall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RabbitTemplate rabbitTemplate;

    private static final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private static final String SKUKILL_CACHE_PREFIX = "seckill:skus";
    private static final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    public final static String ORDER_EVENT_EXCHANGE = "order-event-exchange";
    public final static String ORDER_SECKILL_ORDER_ROUTING_KEY = "order.seckill.order";

    @Override
    public void uploadSeckillSkuLatest3Days() {
        // 1.扫描需要参加秒杀的活动
        R r = couponFeignService.getLatest3DaysSession();
        if(r.getCode() == 0) {
            List<SeckillSessionsWithSkus> sessions = r.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {});
            // 缓存到redis
            // 1.活动信息
            saveSessions(sessions);
            // 2.商品信息
            saveSessionSkus(sessions);
        }
    }

    public List<SeckillSkuRedisTo>  blockHandler(BlockException e) {
        log.error("getCurrentSeckillSkus被限流");
        return null;
    }

    @SentinelResource(value = "getCurrentSeckillSkus", blockHandler = "blockHandler")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        // 资源限流演示
        try(Entry entry = SphU.entry("seckillSkus")) {
            // 确定当前时间属于哪个秒杀场次
            long time = new Date().getTime();
            Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            for (String key : keys) {
                String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                Long start = Long.parseLong(s[0]);
                Long end = Long.parseLong(s[1]);
                if(time >= start && time <= end) {
                    // 获取这个秒杀场次的所有商品信息
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<Object> list = ops.multiGet(range);
                    if(!CollectionUtils.isEmpty(list)) {
                        List<SeckillSkuRedisTo> redisTos = list.stream().map(item -> {
                            SeckillSkuRedisTo redisTo = JSON.parseObject(item.toString(), SeckillSkuRedisTo.class);
                            // 当前秒杀开始,需要随机码
                            // redisTo.setRandomCode(null);
                            return redisTo;
                        }).collect(Collectors.toList());
                        return redisTos;
                    }
                    break;
                }
            }
        } catch (BlockException e) {
            log.error("资源被限流");
        }
        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        // 找到所有需要参与秒杀得商品的key
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = ops.keys();
        if(!CollectionUtils.isEmpty(keys)) {
            String reg = "\\d_" + skuId;
            for (String key : keys) {
                boolean matches = Pattern.matches(reg, key);
                if(matches) {
                    String json = ops.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    // 随机码处理,秒杀时间之外置空
                    Long startTime = redisTo.getStartTime();
                    Long endTime = redisTo.getEndTime();
                    long currentTime = new Date().getTime();
                    if(!(currentTime >= startTime && currentTime <= endTime)) {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String code, Integer num) {
        // 1.获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = ops.get(killId);
        if(!StringUtils.isEmpty(json)) {
            SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
            // 2.校验合法性
            // 2.1 校验时间合法性
            Long time = new Date().getTime();
            Long startTime = redisTo.getStartTime();
            Long endTime = redisTo.getEndTime();
            if(time >= startTime && time <= endTime) {
                // 2.2 校验随机码和商品ID是否正确
                String randomCode = redisTo.getRandomCode();
                String redisKillId = redisTo.getPromotionSessionId() +  "_" + redisTo.getSkuId();
                if(randomCode.equals(code) && killId.equals(redisKillId)) {
                    // 2.3 校验购物数量是否合理
                    if(num <= redisTo.getSeckillLimit().intValue()) {
                        // 2.4 校验是否已购买过
                        // 秒杀成功去redis占位 userId_sessionId_skuId,占位失败说明买过
                        MemberRespVo loginUser = LoginUserInterceptor.loginUser.get();
                        String redisKey = loginUser.getId() + "_" + redisKillId;
                        // 超时时间
                        long ttl = endTime - time;
                        Boolean b = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MICROSECONDS);
                        if(b) {
                            // 3 减库存
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + code);
                            // 等待100毫秒
                            try {
                                boolean b1 = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                                if(b1) {
                                    // 秒杀成功
                                    String timeId = IdWorker.getTimeId();
                                    SeckillOrderTo orderTo = new SeckillOrderTo();
                                    orderTo.setOrderSn(timeId);
                                    orderTo.setMemberId(loginUser.getId());
                                    orderTo.setNum(num);
                                    orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                                    orderTo.setSkuId(redisTo.getSkuId());
                                    orderTo.setSeckillPrice(redisTo.getSeckillPrice());
                                    rabbitTemplate.convertAndSend(ORDER_EVENT_EXCHANGE, ORDER_SECKILL_ORDER_ROUTING_KEY, orderTo);
                                    return timeId;
                                }
                            } catch (InterruptedException e) {
                                log.info("================扣减库存失败 killId:{} code:{} num:{}================", killId, code, num);
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    private void saveSessions(List<SeckillSessionsWithSkus> sessions) {
        if(!CollectionUtils.isEmpty(sessions)) {
            sessions.stream().forEach(session -> {
                long startTime = session.getStartTime().getTime();
                long endTime = session.getEndTime().getTime();
                String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
                Boolean hasKey = redisTemplate.hasKey(key);
                if(!hasKey) {
                    List<String> skuIds = session.getRelationSkus().stream().map(item -> {
                        return item.getPromotionSessionId() + "_" + item.getSkuId().toString();
                    }).collect(Collectors.toList());
                    redisTemplate.opsForList().leftPushAll(key, skuIds);
                }
            });
        }
    }

    private void saveSessionSkus(List<SeckillSessionsWithSkus> sessions) {
        if(!CollectionUtils.isEmpty(sessions)) {
            sessions.stream().forEach(session -> {
                // 准备hash操作
                BoundHashOperations ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                session.getRelationSkus().stream().forEach(sku -> {
                    String key = sku.getPromotionSessionId() + "_" + sku.getSkuId();
                    Boolean hasKey = ops.hasKey(key);
                    if (!hasKey) {
                        SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                        // 1.sku秒杀信息
                        BeanUtils.copyProperties(sku, redisTo);

                        // 2.sku基本信息
                        R r = productFeignService.skuInfo(sku.getSkuId());
                        if (r.getCode() == 0) {
                            SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                            });
                            redisTo.setSkuInfo(skuInfo);
                        }

                        // 3.当前商品秒杀时间信息
                        redisTo.setStartTime(session.getStartTime().getTime());
                        redisTo.setEndTime(session.getEndTime().getTime());

                        // 4.商品随机码
                        // 引入随机码防攻击
                        String token = UUID.randomUUID().toString().replace("-", "");
                        redisTo.setRandomCode(token);

                        // 5.分布式信号量-库存
                        // 信号量作用->限流
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                        semaphore.trySetPermits(sku.getSeckillCount().intValue());

                        String s = JSON.toJSONString(redisTo);
                        ops.put(key, s);
                    }
                });
            });
        }
    }

}
